<template>
  <div>
  <div>
  <el-input
        v-if="inputVisible"
        ref="InputRef"
        v-model="inputValue"
        class="w-20"
        size="small"
        @keyup.enter="handleInputConfirm"
        @blur="handleInputConfirm"
      />
      <el-button style="margin: 0 4px;" v-else plain type="text" bg size="small" @click="showInput">
        +新增标签
      </el-button>
      </div>
    <div>
      <el-tag 
        style="margin: 0 4px;"
        :checked="tag.checked"
        @click="onChange(tag)"
        v-for="tag in dynamicTags"
        :key="tag.tagId"
        :type="tag.type"
        :closable="true"
        :round="true"
        :disable-transitions="true"
        @close="handleClose(tag)"
      >
        {{ tag.tagName }}
      </el-tag>
      
    </div>
    </div>
</template>
  
<script lang="ts" setup>
import { watch, onMounted, nextTick, ref } from 'vue'
import { ElInput } from 'element-plus'
import baseService from "@/service/baseService";

const props = defineProps({
  // modelValue: { type: Object, required: false },
  dishId: { type: Object, required: false }
})

const emit = defineEmits(['update:modelValue'])

const inputValue = ref('')
const dynamicTags = ref([])
const inputVisible = ref(false)
const InputRef = ref<InstanceType<typeof ElInput>>()
const hasFetched = ref(false);

// 保证props.modelValue有值以后才发送请求
// watch(() => props.modelValue, (valNew, valOld) => {
//   if (JSON.stringify(valNew) !== JSON.stringify(valOld) && !hasFetched.value) {
//     taglistRequest();
//   }
// })

// onMounted(() => {
//   if (props.modelValue && !hasFetched.value) {
//     taglistRequest();
//   }
// });

const init = (modelValue) => {
  taglistRequest(modelValue);
};

// 获取信息
const taglistRequest = (modelValue) => {
  baseService.get("/sys/tags/page", {
    page: 1, 
    limit: 10000,
    orderField: "updated_at",
    order: "desc"

  }).then((res) => {
    if (res.code == 0) {
      dynamicTags.value = res.data.list.map((item) => {
        if (modelValue.length > 0 && modelValue.some(mitem => mitem.tagId === item.tagId)) {
          return Object.assign(item, {'checked': true, 'type': 'success'})
        }
        return  Object.assign(item, {'checked': false, 'type': 'info'})
      });
    }
  });
};

const onChange = (tag:any) => {
    dynamicTags.value.forEach(item => {
        if (item.tagName === tag.tagName) {
            item.checked = !item.checked
            item.type = item.checked ? 'success' : 'info'
        }
    })
    emit('update:modelValue', dynamicTags.value)
}

const tagDeleteRequest = (tag) => {
  if (!tag.tagId) {
      dynamicTags.value.splice(dynamicTags.value.indexOf(tag), 1)
      emit('update:modelValue', dynamicTags.value)
  } else {
    baseService.delete("/sys/tags", [props.dishId, tag.tagId]).then((res) => {
    if (res.code == 0) {
      dynamicTags.value.splice(dynamicTags.value.indexOf(tag), 1)
      emit('update:modelValue', dynamicTags.value)
    } else {
      ElMessage.warning({
        message: res.msg,
        duration: 500
      });
    }
  });
  }
  
};
const handleClose = (tag: any) => {
    tagDeleteRequest(tag)
}

const showInput = () => {
    inputVisible.value = true
    nextTick(() => {
        InputRef.value!.input!.focus()
    })
}

const handleInputConfirm = (e) => {
    e.preventDefault()
    e.stopPropagation()
    if (inputValue.value && !dynamicTags.value.some(item => item.tagName === inputValue.value)) {
        dynamicTags.value.push({checked: false, type: "info", tagId: null, tagName: inputValue.value})
    }
    inputVisible.value = false
    inputValue.value = ''
// 调用父组件
    emit('update:modelValue', dynamicTags.value)
}

defineExpose({
  init
});
</script>
  